import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import { staticRoutes } from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router';
import type { reqUserInfoReturnType } from "@/api/userInfo"
import { requestLogin, requestUserInfo, requestLogout } from "@/api/userInfo"
import type { reqLoginParamsType } from "@/api/userInfo"







/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
//直接定义用户信息模块地数据类型
export interface userInfoStateType {
  token: string;
  userInfo: reqUserInfoReturnType;
  menuRoutes: RouteRecordRaw[];
}
export const useUserInfoStore = defineStore('userInfo', {
  state: (): userInfoStateType => ({
    token: (getToken() as string) || '',
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    //把静态路由表保存起来，遍历路由表生成侧边栏元素
    menuRoutes: staticRoutes
  }),

  actions: {
    //1.登录的方法
    async login(userInfo: reqLoginParamsType) {
      try {
        //方法登录请求
        const result = await requestLogin(userInfo)
        //把请求回来的token保存到satte中
        this.token = result.token
        //登录持久化
        setToken(this.token)
      } catch (e) {
        //返回失败的Promise实例，为了以后在哪里调用这个方法出现异常了，就在哪里处理异常
        return Promise.reject(e)
      }
    },

    //2.获取用户信息的方法
    async getInfo() {
      try {
        //发送用户信息请求
        const result = await requestUserInfo()
        //把请求回来的用户信息保存在state中
        this.userInfo = result
      } catch (e) {
        //抛出异常
        return Promise.reject(e)
      }
    },

    //3.退出登录请求
    async getLogout() {
      try {
        //发送退出登录请求
        await requestLogout()
        //清空用户信息
        this.reset()
      } catch (e) {
        //抛出异常
        return Promise.reject(e)
      }
    },

    //4.清空用户信息
    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = '',
        this.userInfo = {
          routes: [],
          buttons: [],
          roles: [],
          name: "",
          avatar: "",
        }
    },
  },
});
